//
//  GLDBViewController_Detail_B.m
//  Estate
//
//  Created by heyong on 16/6/24.
//  Copyright © 2016年 ttsx. All rights reserved.
//
#define LINE_Y 20
#import "GLDBViewController_Detail_B.h"
#import "UIActionSheet+Common.h"
#import "PictureViewController.h"

#import "AttachmentPhotoCell.h"

@interface GLDBViewController_Detail_B ()<UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

// 整改前
@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;
@property (nonatomic, strong) UITableView  *tableView;
@property (strong, nonatomic) Tweet *curTweet;

// 整改后
@property (strong, nonatomic) NSMutableArray *selectedAssetURLs2;
@property (nonatomic, strong) UITableView *tableView2;
@property (strong, nonatomic) Tweet *curTweet2;

@end

@implementation GLDBViewController_Detail_B

// 整改前
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, DEF_SCREEN_WIDTH / 2 , DEF_SCREEN_HEIGHT-154) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerClass:[AttachmentPhotoCell class] forCellReuseIdentifier:@"photoCell"];
    }
    return _tableView;
}

- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

// 整改后
- (UITableView *)tableView2 {
    if (!_tableView2) {
        _tableView2 = [[UITableView alloc] initWithFrame:CGRectMake(DEF_SCREEN_WIDTH / 2, 40, DEF_SCREEN_WIDTH / 2 , DEF_SCREEN_HEIGHT-154) style:UITableViewStylePlain];
        _tableView2.tag = 2000;
        _tableView2.backgroundColor = [UIColor whiteColor];
        [_tableView2 registerClass:[AttachmentPhotoCell class] forCellReuseIdentifier:@"photoCell"];
    }
    return _tableView2;
}

- (NSMutableArray *)selectedAssetURLs2 {
    if (!_selectedAssetURLs2) {
        _selectedAssetURLs2 = [NSMutableArray array];
    }
    return _selectedAssetURLs2;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self createView];
    
    _curTweet = [[Tweet alloc] init];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.bounces=NO;
    self.tableView.showsVerticalScrollIndicator=NO;
    self.tableView.separatorStyle = NO;
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    _curTweet2 = [[Tweet alloc] init];
    self.tableView2.dataSource = self;
    self.tableView2.delegate = self;
    [self.view addSubview:self.tableView2];
    self.tableView2.bounces=NO;
    self.tableView2.showsVerticalScrollIndicator=NO;
    self.tableView2.separatorStyle = NO;
    self.tableView2.backgroundColor = [UIColor whiteColor];
    
    
    [self accessAttachment];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_sgf" object:nil];
}

- (void)refresh:(id)sender{
    if(self.selectedAssetURLs2 != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet2.selectedAssetURLs = self.selectedAssetURLs2;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView2 reloadData];
            });
        });
    }
}

-(void)addAssetURLArrayto:(NSMutableArray *)assetURLArray fromImageArrray:(ProcessRecordModel *)recordModel{
    NSArray *imageArr = [LSUtility dictionaryWithJsonString:recordModel.FILEINFOS];
    
    if (imageArr.count>0) {
        for (NSDictionary *imageDic in imageArr) {
            NSString *fileId = imageDic[@"fileId"];
            NSString *fileName = [LSUtility queryAttachment:fileId][@"FILE_NAME"];
            NSString *filePath = [DEF_FILE_PATH stringByAppendingString:
                                  [NSString stringWithFormat:@"/%@",fileName]];
            [assetURLArray addObject:filePath];
        }
    }
}
-(void)accessAttachment{
    
    //如果一条 肯定为整改前
    if (self.processRecoedArray.count <= 1) {
        self.lastRecordM = [self.processRecoedArray firstObject];
        [self addAssetURLArrayto:self.selectedAssetURLs fromImageArrray:self.lastRecordM];
    }else{
        //如果督办 肯定第一条整改前 最后一条整改后
        if (self.duban) {
            self.lastRecordM = [self.processRecoedArray firstObject];
            [self addAssetURLArrayto:self.selectedAssetURLs2 fromImageArrray:self.lastRecordM];
            self.firstRecordM = [self.processRecoedArray lastObject];
            [self addAssetURLArrayto:self.selectedAssetURLs fromImageArrray:self.firstRecordM];
            
            
        }else if (self.genjin){
            //如果2条 总监审阅完 取出最新一条为整改前
            if (self.processRecoedArray.count==2) {
                self.lastRecordM = self.processRecoedArray[0];
                [self addAssetURLArrayto:self.selectedAssetURLs fromImageArrray:self.lastRecordM];
            }else{
                self.lastRecordM = [self.processRecoedArray firstObject];
                [self addAssetURLArrayto:self.selectedAssetURLs2 fromImageArrray:self.lastRecordM];
                
                self.firstRecordM = self.processRecoedArray[self.processRecoedArray.count-2];
                [self addAssetURLArrayto:self.selectedAssetURLs fromImageArrray:self.firstRecordM];
                
            }
        }
    }
    if (self.lastRecordM.PROCESS_STAGE == PROCESS_STAGE_CHECK&&self.lastRecordM.SEND_TYPE==4&&self.lastRecordM.PROCESS_TYPE == PROCESS_TYPE_SUPERVISE) {
        self.isEdit = YES;
    }
    self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
    self.curTweet2.selectedAssetURLs = self.selectedAssetURLs2;
    [self.tableView reloadData];
    [self.tableView2 reloadData];
    
}
- (void)createView{
    //添加分割线
    UIView *line_1=[[UIView alloc]initWithFrame:CGRectMake(0, LINE_Y, DEF_SCREEN_WIDTH, 1)];
    
    line_1.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:1.00];
    
    UIView *line_2=[[UIView alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/2-0.5, LINE_Y, 1, DEF_SCREEN_HEIGHT-10)];
    
    line_2.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:1.00];
    
    [self.view addSubview:line_1];
    
    [self.view addSubview:line_2];
    
    //添加文字
    UILabel *lab_1=[[UILabel alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/8, LINE_Y/2, DEF_SCREEN_WIDTH/4, LINE_Y)];
    
    lab_1.text=@"整改前附件";
    
    lab_1.textAlignment=1;
    
    lab_1.backgroundColor=[UIColor whiteColor];
    
    lab_1.font=[UIFont systemFontOfSize:14.];
    
    [self.view addSubview:lab_1];
    
    UILabel *lab_2=[[UILabel alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/8*5, LINE_Y/2, DEF_SCREEN_WIDTH/4, LINE_Y)];
    
    lab_2.text=@"整改后附件";
    
    lab_2.textAlignment=1;
    
    lab_2.backgroundColor=[UIColor whiteColor];
    
    lab_2.font=[UIFont systemFontOfSize:14.];
    
    [self.view addSubview:lab_2];
    
}

#pragma mark - UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 2000) {
        return [AttachmentPhotoCell cellHeightWithObj:_curTweet2];
    } else {
        return [AttachmentPhotoCell cellHeightWithObj:_curTweet];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    AttachmentPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"photoCell" forIndexPath:indexPath];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.isEdit = NO;
    if (tableView.tag == 2000) {
        cell.isEdit = self.isEdit;
        cell.curTweet = _curTweet2;
        cell.addPicturesBlock = ^(){
            
            [weakSelf showActionForPhoto:_curTweet2];
        };
    } else {
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            
            [weakSelf showActionForPhoto:_curTweet];
        };
    }
    
    cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
        //移除图片
        [weakSelf.curTweet2 deleteATweetImage:toDelete];
        //移除数组
        [weakSelf.selectedAssetURLs2 removeObject:deUrl];
        
        [weakSelf refresh:nil];
    };
    return cell;
}


/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
#pragma mark UIActionSheet M
- (void)showActionForPhoto:(Tweet *)tweet{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index tweet:tweet];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex tweet:(Tweet *)tweet{
    if (buttonIndex == 0) {
        //拍照
        if (tweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO; // 设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs2 valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages = [[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock = ^(NSMutableArray *array){
            self.selectedAssetURLs2 = [NSMutableArray arrayWithArray:array];
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet2 addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs2 addObject:path];
        //刷新指定行
        [weakSelf.tableView2 reloadData];
        
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RefreshImage_sgf" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updateAttachment" object:nil];
}
- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveImage) name:@"updateAttachment" object:nil];
}

- (void)saveImage {
    // 流程记录ID
    NSString *recordId = [NSUUID UUID].UUIDString;
    // 附件信息
    NSArray *fileinfosArr = [self insertAttachment:recordId];
    NSString *fileinfosStr;
    if (fileinfosArr) {
        fileinfosStr = [LSUtility toJSONData:fileinfosArr];
    } else {
        fileinfosStr = @"";
    }
    NSDictionary *dic = @{@"ID":recordId, @"ARRAY":fileinfosStr};
    
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"succeedSGFDaiBan" object:nil userInfo:dic]];
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"succeedJLDuBan" object:nil userInfo:dic]];
    
}

#pragma mark - 新增附件表
- (NSArray *)insertAttachment:(NSString *)recordIds {
    NSArray *rFileArr;
    if (self.selectedAssetURLs2.count > 0) {
        NSString *processType;
        if (self.lastRecordM.PROCESS_TYPE == 1) {
            processType = @"PROCESS_01";
        } else if (self.lastRecordM.PROCESS_TYPE == 2) {
            processType = @"PROCESS_02";
        }
        rFileArr = [LSUtility insertAttachmentFromArray:self.selectedAssetURLs2 andRecordId:recordIds andType:processType andRecifyState:@"1"];
    }
    return rFileArr;
}
@end

